<?php
namespace Home\Controller;
use Think\Controller;

class UploadController extends Controller {
	function __construct() {
		
	}
	
	
	function upload(){
		$dir = I('get.dir', 'image');
		// $image = new \Think\Image();
		$file = $_FILES['Filedata'];
		$finfo = pathinfo($file['name']);
		switch ($dir) {
			case 'image':
				$fileTypes = array('jpg','jpeg','gif','png','bmp');
				break;
			case 'videos':
				$fileTypes = array('mp4');
				break;
			default:
				$this->ajaxReturn(array('s'=>false,'m'=>'上传文件夹类型错误'));
				break;
		}
		$SAVE_PATH = ''.C('UPLOAD_PATH')."/{$dir}/";
		if(!in_array(strtolower($finfo['extension']), $fileTypes)){
			$this->ajaxReturn(array('s'=>false,'m'=>'不允许上传的文件格式', 'extension'=>$finfo['extension'], 'fileTypes'=>$fileTypes));
		}
		$filename = $SAVE_PATH.date('ymd_his_').mt_rand(1000,9999).'.'.$finfo['extension'];
		
		$rs = move_uploaded_file($file['tmp_name'], $filename);
		if(!$rs){
			$this->ajaxReturn(array('s'=>false,'m'=>'文件上传失败', 'file'=>$file));
		}
		$this->ajaxReturn(array('s'=>true,'m'=>'Success','d'=>C('SiteUrl').$filename)); 
	} 


	function uploadtow(){
		$image = new \Think\Image();
		
		$file = $_FILES['Filedata'];
		$finfo = pathinfo($file['name']);
		
		$SAVE_PATH = ''.C('UPLOAD_PATH').'/image/';
		
		$exe = strtolower($finfo['extension']);
		$filename = $SAVE_PATH.date('ymd_his_').mt_rand(1000,9999).'.'.$exe;
		
		$fileTypes = array('jpg','jpeg','gif','png','bmp');
		
		if(!in_array($exe,$fileTypes)){
			$this->ajaxReturn(array('s'=>false,'m'=>'不允许上传的文件格式'));
		}
		
		$rs = move_uploaded_file($file['tmp_name'],$filename);
		
		if(!$rs){
			$this->ajaxReturn(array('s'=>false,'m'=>'文件上传失败'));
		}
		// Watermark('/'.$filename);
		$this->ajaxReturn(array('s'=>true,'m'=>'Success','d'=>C('SiteUrl').$filename)); 
	} 
	
	function delfile(){
		$path = I('post.filepath');
		if(empty($path)){
			$this->ajaxReturn(array('s'=>false,'m'=>'参数错误'));
		}
		$path = $_SERVER['DOCUMENT_ROOT'].$path;
		if(!file_exists($path)){
			$this->ajaxReturn(array('s'=>false,'m'=>'文件不存在','d'=>$path));
		}
		$rs = @unlink( $path );
		if(!$rs){
			$this->ajaxReturn(array('s'=>false,'m'=>'文件删除失败'));
		}
		$this->ajaxReturn(array('s'=>true,'m'=>'文件删除完成'));
	}
}